#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import sys
import md5
import json
import time
import fileutils

cwd = os.getcwd()
save_dir = os.path.join(cwd, 'md5.json')
temp_dir = os.path.join(cwd, 'md5_.json')
gen_dir = os.path.join(cwd, 'gen')
manifest = os.path.join(gen_dir, 'project.manifest')
manifest_temp = os.path.join(gen_dir, 'project.manifest.temp')
manifest_zip = os.path.join(gen_dir, 'project.manifest.zip')
win_rar_exec = os.path.join(cwd, 'WinRAR', 'WinRAR.exe')

def clear():
    fileutils.rmtree(gen_dir)
    pass

def read_md5(src):
    js_obj = {}
    if os.path.isfile(src):
        try:
            with open(src, 'r') as f:
                js_str = f.read()
                js_obj = json.loads(js_str)
            pass
        except Exception as e:
            print (e.message)
            pass
        
    return js_obj

def save_md5():
    fileutils.copyfile(temp_dir, save_dir)
    pass

def finish():
    save_md5()
    return True

def compare(a, b):
    if a == None or b == None:
        return False
    if a == '' or b == '':
        return False
    return a == b

def chdir(dir):
    os.chdir(dir)
    pass

def win_rar(version):
    os.chdir(gen_dir)
    ret = False
    cmd = '%s a %s ./project.manifest.temp' % (win_rar_exec, manifest_zip)
    if os.system(cmd) != 0:
        os.chdir(cwd)
        return ret
    
    zip_name = './%s.zip' % (version)
    cmd = '%s a -r %s ./*' % (win_rar_exec, zip_name)
    if os.system(cmd) != 0:
        os.chdir(cwd)
        return ret

    os.chdir(cwd)
    return True

def make_manifest(diff):
    ret = False
    f = None

    if not os.path.isdir(gen_dir):
        os.makedirs(gen_dir)

    try:
        f = open(manifest, 'w')
        pass
    except Exception as e:
        print (e.message)
        return ret
        pass

    version = gen_version(manifest)

    assets = {}
    for k, v in diff.items():
        file = gen_dir + k
        if not os.path.isfile(file):
            continue

        t = {}
        t['md5'] = v
        t['size'] = os.path.getsize(file)
        t['version'] = version
        assets[k] = t

    if len(assets) == 0:
        return ret

    projcet = {}
    projcet['assets'] = assets
    projcet['date'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    projcet['git'] = ''
    projcet['packageUrl'] = '/'
    projcet['remoteManifestUrl'] = '/project.manifest'
    projcet['remoteVersionUrl'] = '/version.manifest'
    projcet['version'] = version
    projcet['zipRemoteManifestUrl'] = '/project.manifest.temp.zip'

    try:
        js_str = json.dumps(projcet)
        f.write(js_str)
        f.close()

        fileutils.copyfile(manifest, manifest_temp)
        pass
    except Exception as e:
        print (e.message)
        return ret
        pass

    if not win_rar(version):
        print ('win_rar ret False .')
        return ret

    ret = True
    return ret

def gen_version(file):
    t = time.time()
    m = md5.getmd5(file)
    return '%s_%s' % (int(t), m)

def gen_res(src):
    clear()
    md5.genmd5(src, temp_dir)
    js_obj = read_md5(save_dir)
    js_t_obj = read_md5(temp_dir)
    diff = {}
    for k, v in js_t_obj.items():
        #print (v)
        a = v
        b = ''
        if k in js_obj:
            b = js_obj[k]
        
        if compare(a, b):
            continue

        _in = fileutils.separator(src + k)
        _out = fileutils.separator(gen_dir + k)
        if not fileutils.copyfile(_in, _out):
            continue

        diff[k] = v
        #print (k)
    if len(diff) == 0:
        print ('%s not diff .' % src)
        return

    if not make_manifest(diff):
        print ('make_manifest ret False')
        return

    if finish():
        print ('%s gen finish .' % src)
        print ('%s out .' % gen_dir)
    pass

if __name__ == '__main__':
    #src = 'E:\git\SoLoader\console'
    args = sys.argv

    if len(args) == 2:
        src = args[1]
        print (src)
        gen_res(src)